<template>
    <!-- 卡片 -->
    <el-card shadow="always" :body-style="{ padding: '20px' }">
        <template #header>
            <el-button type="primary" :icon="Plus" @click="addTrademark">添加</el-button>
        </template>
        <!-- 表格 -->
        <el-table style="margin-bottom: 30px" :data="tableData" stripe border>
            <el-table-column align="center" type="index" label="序号" width="80" />
            <el-table-column prop="tmName" label="品牌名称" ></el-table-column>
            <el-table-column prop="logoUrl" label="品牌LOGO">
                <template #default="{row}">
                    <img :src="row.logoUrl" height="80"/>
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template #default="{row}">
                    <el-button type="warning" :icon="Edit" @click="updateTrademark(row)">修改</el-button>
                    <el-button type="danger" :icon="DeleteFilled" @click="deleteTrademark(row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页器 -->
        <el-pagination 
            v-model:current-page="page"
            v-model:page-size="limit"
            :pager-count="7"
            :total="total"
            :page-sizes="[3, 5, 7, 10]"
            layout="prev, pager, next , sizes , total"
        ></el-pagination>
    </el-card>

    <!-- 弹窗 -->
    <el-dialog v-model="dialogFormVisible" :title="newTrademark.id? '修改商品' : '新增商品' ">
        <el-form label-width="100px" :model="newTrademark" :rules="trademarkRules" ref="fromEle">
        <el-form-item label="品牌名称" prop="tmName">
            <el-input  autocomplete="off" v-model="newTrademark.tmName"/>
        </el-form-item>
        <el-form-item label="品牌LOGO" prop="logoUrl">
            <!-- 上传 -->
            <el-upload
                class="avatar-uploader"
                :action="`${baseUrl}/admin/product/upload`"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
            >
                <img v-if="newTrademark.logoUrl" :src="newTrademark.logoUrl" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
        </el-form-item>
        </el-form>
        <!-- 底部按钮 -->
        <template #footer>
        <span class="dialog-footer">
            <el-button @click="">取消</el-button>
            <el-button type="primary" @click="updateOrAddTrademark">确定</el-button>
        </span>
        </template>
    </el-dialog>

</template>

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
    name: "Tardemark",
});
</script>

<script setup lang="ts">
import { Plus , Edit , DeleteFilled} from "@element-plus/icons-vue"
import { ref , toRefs , onMounted , watch , reactive} from "vue"
import type { reqTrademarkReturnRecordsType , reqTrademarkReturnItemType} from "@/api/tradmark"
import {requestTrademarkList , requestUpdateTrademark , requestAddTrademark , requestDeleteTrademark} from "@/api/tradmark"
import { ElMessage  , ElMessageBox , ElNotification} from 'element-plus'
import type { UploadProps , FormRules , FormInstance} from 'element-plus'

//1.table逻辑
//table需要的数据，请求没回来之前是空数组，请求回来就有值了
const tableData = ref<reqTrademarkReturnRecordsType>([])


//2.页码逻辑
//页码数据的类型
interface pageDateType{
    page: number
    limit: number
    total: number
}
//定义页码数据
const pageDate = ref<pageDateType>({
    page: 1,
    limit: 3,
    total: 100
})
//解构页码数据
const {page , limit , total} = toRefs(pageDate.value)


//3.获取商品列表
const getTrademarkList = async () => {
    //发请求
    const result = await requestTrademarkList({page: page.value , limit: limit.value})
    //把响应的表格的数据给数组
    tableData.value = result.records
    //把总页树给total
    total.value = result.total
}
//初始化请求商品详情
onMounted(() => {
    //初始化发送商品列表请求
    getTrademarkList()
});
//监听页码的改变发送商品列表请求
watch([page , limit] , () => {
    //重新发送商品列表请求
    getTrademarkList()
})


//4.弹窗逻辑
//定义数据保存控制弹窗的显示隐藏
const dialogFormVisible = ref(false)
//路径前缀
const baseUrl = import.meta.env.VITE_API_URL;
//定义数据保存一条要添加的数据
const newTrademark = ref<reqTrademarkReturnItemType>({
    id: 0,
    tmName: "",
    logoUrl: ""
})

//上传成功的回调
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  //上传成功后返回的图片保存到数据中
  newTrademark.value.logoUrl = response.data
  //图片有值之后清空表单校验的错误提示
  fromEle.value?.clearValidate("logoUrl")
}
//上传之前的回调
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}

//5.点击添加的逻辑
const addTrademark = () => {
    //添加之前清空表单校验的错误信息
    fromEle.value?.clearValidate()
    //展示弹窗
    dialogFormVisible.value = true
    //清空弹窗数据
    newTrademark.value = {
        id: 0,
        tmName: "",
        logoUrl: ""
    }
}
//6.点击修改的逻辑
const updateTrademark = (row: reqTrademarkReturnItemType) => {
    //修改之前清空表单校验的错误信息
    fromEle.value?.clearValidate()
    //展示弹窗
    dialogFormVisible.value = true
    //获取当前数据，然后回填
    newTrademark.value =  {...row}
}


//7.新增和修改的提交
//获取表单元素
const fromEle = ref<FormInstance>()
const updateOrAddTrademark = async () => {
    try {

        //提交之前表单校验
        await fromEle.value?.validate()


        //表单校验成功才执行提交逻辑
        //关闭弹窗
        dialogFormVisible.value = false
        try {
            //判断是新增还是修改
            if(newTrademark.value.id){
                //发送修改请求
                await requestUpdateTrademark(newTrademark.value)
                //提示
                ElMessage.success("修改成功")
            }else{
                //发送新增请求
                await requestAddTrademark(newTrademark.value)
                ElMessage.success("新增成功")
                //新增成功默认显示第一页
                page.value = 1
            }
            //修改成功或者添加成功都重新请求列表
            getTrademarkList()
        } catch (error) {
            ElMessage.error(newTrademark.value.id? '修改失败' : '新增失败')
        }

    } catch (error) {
        ElMessage.error("表单校验失败")
    } 
}

//8.删除逻辑
const deleteTrademark = (id: number) => {
    //删除之前提示
    ElMessageBox.confirm('确定要删除吗?','警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
    .then( async ()=>{
        //确定删除就执行删除的操作
        try {
            //发送删除请求
            await requestDeleteTrademark(id)
            // //删除成功提示
            ElNotification({
                title: 'Success',
                message: '删除成功',
                type: 'success',
                position: 'top-left',
            })
            //重新渲染
            getTrademarkList()
        } catch (error) {
            //手删除失败提示
            ElMessage.error("删除失败!")
        }
    })
    .catch(()=>{
        //取消删除弹出提示
        ElNotification({
                title: 'cancel',
                message: '取消成功',
                type: 'success',
                position: 'top-right',
        })
    })
}

//自定义表单校验规则
const mayRules = (rule: any, value:string , callback: any) => {
    if(value.length < 2 || value.length > 5){
        callback("长度不符合规则!")
    }else{
        callback()
    }
}
//9.表单校验规则
const trademarkRules =  reactive<FormRules>({
    //商品名称的规则
    tmName:[
        { required: true, message: '输入内容不能为空!'  , trigger: 'blur' },
        //自定义表单校验规则
        { validator: mayRules ,  trigger: 'blur' },
    ],
    //上传图片
    logoUrl:[
        { required: true, message: '输入内容不能为空!', trigger: 'change' },
    ]
})


</script>

<style scoped>
    .el-button--text {
      margin-right: 15px;
    }
    .el-select {
      width: 300px;
    }
    .el-input {
      width: 300px;
    }
    .dialog-footer button:first-child {
      margin-right: 10px;
    }

    .avatar-uploader .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }

</style>
<style>
    .avatar-uploader .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }
    
    .avatar-uploader .el-upload:hover {
      border-color: var(--el-color-primary);
    }
    
    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
</style>